package com.canaan.business.service.storehouse.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum;
import com.canaan.business.common.enums.inOutStock.StockOccupyTypeEnum;
import com.canaan.business.common.enums.storehouse.StorehouseStockStatusEnum;
import com.canaan.business.domain.inOutStock.StockOccupyDetail;
import com.canaan.business.domain.inOutStock.WmsStockOccupy;
import com.canaan.business.domain.storehouse.StockFreeze;
import com.canaan.business.domain.storehouse.WmsStorehouseStock;
import com.canaan.business.mapper.inOutStock.StockOccupyDetailMapper;
import com.canaan.business.mapper.inOutStock.WmsStockOccupyMapper;
import com.canaan.business.mapper.storehouse.StockFreezeMapper;
import com.canaan.business.mapper.storehouse.WmsStorehouseStockMapper;
import com.canaan.business.service.storehouse.IStockFreezeService;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.SecurityUtils;
import com.canaan.common.utils.StringUtils;
import com.canaan.common.utils.TableNoUtil;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 库存冻结Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-08
 */
@Service
public class StockFreezeServiceImpl implements IStockFreezeService {

    @Resource
    private StockFreezeMapper stockFreezeMapper;

    @Resource
    private WmsStockOccupyMapper wmsStockOccupyMapper;

    @Resource
    private WmsStorehouseStockMapper storehouseStockMapper;

    @Resource
    private StockOccupyDetailMapper stockOccupyDetailMapper;

    /**
     * 查询库存冻结
     *
     * @param id 库存冻结主键
     * @return 库存冻结
     */
    @Override
    public StockFreeze selectStockFreezeById(Long id) {
        return stockFreezeMapper.selectStockFreezeById(id);
    }

    /**
     * 查询库存冻结列表
     *
     * @param stockFreeze 库存冻结
     * @return 库存冻结
     */
    @Override
    public List<StockFreeze> selectStockFreezeList(StockFreeze stockFreeze) {
        return stockFreezeMapper.selectStockFreezeList(stockFreeze);
    }

    /**
     * 新增库存冻结
     *
     * @param stockFreeze 库存冻结
     * @return 结果
     */
    @Override
    public String insertStockFreeze(StockFreeze stockFreeze) {

        List<StockFreeze> stockFreezeList = this.selectStockFreezeList(stockFreeze);
        if(!stockFreezeList.isEmpty()){
            throw new ServiceException("所选冻结数据已存在!!");
        }

        WmsStorehouseStock wss = new WmsStorehouseStock();
        wss.setBarcode(stockFreeze.getBarcode());
        wss.setProductNo(stockFreeze.getProductNo());
        wss.setProductName(stockFreeze.getProductName());
        wss.setBatchNo(stockFreeze.getLotNo());
        List<WmsStorehouseStock> wssList = storehouseStockMapper.selectWmsStorehouseStockList(wss);
        List<WmsStorehouseStock> normalStockList = wssList.stream().filter(a -> StorehouseStockStatusEnum.NORMAL.getCode().equals(a.getStatus())).collect(Collectors.toList());
        if(normalStockList.isEmpty()){
            throw new ServiceException("所选物料数据不匹配!");
        }

        if(StringUtils.isBlank(stockFreeze.getNo())){
            stockFreeze.setNo(TableNoUtil.getNo(StockFreeze.class));
        }
        stockFreeze.setCreateBy(SecurityUtils.getUsername());
        stockFreeze.setCreateTime(DateUtils.getNowDate());
        stockFreezeMapper.insertStockFreeze(stockFreeze);
        return stockFreeze.getNo();
    }

    /**
     * 批量新增库存冻结
     *
     * @param stockFreezeList 库存冻结列表
     * @return 结果
     */
    @Override
    public int batchInsertStockFreeze(List<StockFreeze> stockFreezeList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (StockFreeze stockFreeze : stockFreezeList){
            if(StringUtils.isBlank(stockFreeze.getNo())){
                stockFreeze.setNo(TableNoUtil.getNo(StockFreeze.class));
            }
            stockFreeze.setCreateBy(username);
            stockFreeze.setCreateTime(currerTime);
        }
        int insertNum = 0;
        for (int i=0; i<stockFreezeList.size();) {
            int endIndex = i+500;
            if (endIndex > stockFreezeList.size()) {
                endIndex = stockFreezeList.size();
            }
            insertNum = insertNum + stockFreezeMapper.batchInsertStockFreeze(stockFreezeList.subList(i, endIndex));
            i = endIndex;
        }
        return insertNum;
    }

    /**
     * 修改库存冻结
     *
     * @param stockFreeze 库存冻结
     * @return 结果
     */
    @Override
    public int updateStockFreeze(StockFreeze stockFreeze) {
        List<StockFreeze> stockFreezeList = this.selectStockFreezeList(stockFreeze);
        if(!stockFreezeList.isEmpty()){
            stockFreezeList = stockFreezeList.stream().filter(e->!e.getNo().equals(stockFreeze.getNo())).collect(Collectors.toList());
            if (stockFreezeList.size()>0){
                throw new ServiceException("所选冻结数据已存在!!");
            }
        }
        WmsStorehouseStock wss = new WmsStorehouseStock();
        wss.setBarcode(stockFreeze.getBarcode());
        wss.setProductNo(stockFreeze.getProductNo());
        wss.setProductName(stockFreeze.getProductName());
        wss.setBatchNo(stockFreeze.getLotNo());
        List<WmsStorehouseStock> wssList = storehouseStockMapper.selectWmsStorehouseStockList(wss);
        if(wssList.isEmpty()){
            throw new ServiceException("所选物料数据不匹配!");
        }

        stockFreeze.setUpdateBy(SecurityUtils.getUsername());
        stockFreeze.setUpdateTime(DateUtils.getNowDate());
        return stockFreezeMapper.updateStockFreeze(stockFreeze);
    }

    /**
     * 批量修改库存冻结
     *
     * @param stockFreezeList 库存冻结列表
     * @return 结果
     */
    @Override
    public int batchUpdateStockFreeze(List<StockFreeze> stockFreezeList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (StockFreeze stockFreeze : stockFreezeList){
            stockFreeze.setUpdateBy(username);
            stockFreeze.setUpdateTime(currerTime);
        }
        int updateNum = 0;
        for (int i=0; i<stockFreezeList.size();) {
            int endIndex = i+500;
            if (endIndex > stockFreezeList.size()) {
                endIndex = stockFreezeList.size();
            }
            updateNum = updateNum + stockFreezeMapper.batchUpdateStockFreeze(stockFreezeList.subList(i, endIndex));
            i = endIndex;
        }
        return updateNum;
    }

    /**
     * 批量删除库存冻结
     *
     * @param ids 需要删除的库存冻结主键集合
     * @return 结果
     */
    @Override
    public int deleteStockFreezeByIds(Long[] ids) {
        return stockFreezeMapper.deleteStockFreezeByIds(ids);
    }

    /**
     * 删除库存冻结信息
     *
     * @param id 库存冻结主键
     * @return 结果
     */
    @Override
    public int deleteStockFreezeById(Long id) {
        return stockFreezeMapper.deleteStockFreezeById(id);
    }

    @Override
    public List<String> importExcel(List<StockFreeze> list) {
        List<String> errorList = Lists.newArrayList();

        for (int i = 0; i < list.size(); i++) {
            WmsStorehouseStock wss = new WmsStorehouseStock();
            wss.setBarcode(list.get(i).getBarcode());
            wss.setProductNo(list.get(i).getProductNo());
            wss.setProductName(list.get(i).getProductName());
            wss.setBatchNo(list.get(i).getLotNo());
            List<WmsStorehouseStock> wssList = storehouseStockMapper.selectWmsStorehouseStockList(wss);
            if(wssList.isEmpty()){
                errorList.add("第" + ( i + 1 ) + "行所选物料数据不匹配!");
            }
        }

        if(errorList.size() > 0){
            return errorList;
        }

        this.batchInsertStockFreeze(list);

        return errorList;
    }

    @Override
    public int activationStockFreezeAndOccupy(Long id) {

        StockFreeze stockFreeze = this.selectStockFreezeById(id);

        WmsStockOccupy stockOccupy = new WmsStockOccupy();
        if(StringUtils.isBlank(stockOccupy.getNo())){
            stockOccupy.setNo(TableNoUtil.getNo(WmsStockOccupy.class));
        }
        stockOccupy.setStatus(StockOccupyStatusEnum.VALID.getCode());
        stockOccupy.setTaskNo(stockFreeze.getNo());
        stockOccupy.setType(StockOccupyTypeEnum.FREEZE.getCode());
        stockOccupy.setCreateBy(SecurityUtils.getUsername());
        stockOccupy.setCreateTime(DateUtils.getNowDate());
        wmsStockOccupyMapper.insertWmsStockOccupy(stockOccupy);

        WmsStorehouseStock stock = new WmsStorehouseStock();
        stock.setBatchNo(stockFreeze.getLotNo());
        stock.setProductNo(stockFreeze.getProductNo());
        stock.setBarcode(stockFreeze.getBarcode());
        stock.setStorehouseNo(stockFreeze.getStorehouseNo());
        List<WmsStorehouseStock> storehouseStockList = storehouseStockMapper.selectWmsStorehouseStockList(stock);
        if(!storehouseStockList.isEmpty()){

            List<StockOccupyDetail> occupyDetails = Lists.newArrayList();
            for (WmsStorehouseStock storehouseStock : storehouseStockList){

                storehouseStock.setStatus(StorehouseStockStatusEnum.FREEZE.getCode());
                storehouseStock.setOccupyQty(storehouseStock.getQty());

                StockOccupyDetail detail = new StockOccupyDetail();
                detail.setBarcode(storehouseStock.getBarcode());
                detail.setNo(TableNoUtil.getNo(StockOccupyDetail.class));
                detail.setProductNo(storehouseStock.getProductNo());
                detail.setStockOccupyNo(stockOccupy.getNo());
                detail.setOccupyQty(storehouseStock.getQty());
                detail.setStorehouseLocationNo(storehouseStock.getStorehouseLocationNo());
                occupyDetails.add(detail);
            }

            storehouseStockMapper.batchUpdateWmsStorehouseStock(storehouseStockList);
            stockOccupyDetailMapper.batchInsertStockOccupyDetail(occupyDetails);
        }
        //激活冻结
        stockFreeze.setIsActivation("1");
        this.updateStockFreeze(stockFreeze);
        return 1;
    }

    @Override
    public int removeActivationStockFreezeAndOccupy(Long id) {
//        StockFreeze freeze = new StockFreeze();
//        freeze.setId(id);
//        List<StockFreeze> freezes = this.selectStockFreezeList(freeze);
//
//        List<String> occupyNos = freezes.stream().map(StockFreeze::getNo).collect(Collectors.toList());
        StockFreeze stockFreeze = this.selectStockFreezeById(id);

        WmsStockOccupy occupy = new WmsStockOccupy();
        occupy.setTaskNo(stockFreeze.getNo());
        List<WmsStockOccupy> occupyList = wmsStockOccupyMapper.selectWmsStockOccupyList(occupy);
        for (WmsStockOccupy occupy1 : occupyList){
            occupy1.setStatus(StockOccupyStatusEnum.INVALID.getCode());
        }
        if (!occupyList.isEmpty()){
            wmsStockOccupyMapper.batchUpdateWmsStockOccupy(occupyList);
        }

        List<WmsStorehouseStock> updateStockList = Lists.newArrayList();
//        for (StockFreeze stockFreeze : freezes){
        WmsStorehouseStock stock = new WmsStorehouseStock();
        stock.setBatchNo(stockFreeze.getLotNo());
        stock.setProductNo(stockFreeze.getProductNo());
        stock.setBarcode(stockFreeze.getBarcode());
        stock.setStorehouseNo(stockFreeze.getStorehouseNo());
        List<WmsStorehouseStock> storehouseStockList = storehouseStockMapper.selectWmsStorehouseStockList(stock);
        for (WmsStorehouseStock storehouseStock : storehouseStockList){
            storehouseStock.setStatus(StorehouseStockStatusEnum.NORMAL.getCode());
            storehouseStock.setOccupyQty(0L);
            updateStockList.add(storehouseStock);
        }
//        }
        storehouseStockMapper.batchUpdateWmsStorehouseStock(updateStockList);

        //取消激活冻结
        stockFreeze.setIsActivation("0");
        this.updateStockFreeze(stockFreeze);
        return 1;
    }
}
